package com.abss.vote.controller;

import com.abss.vote.model.*;
import com.abss.vote.service.RedisService;
import com.abss.vote.service.UserBackstageService;
import com.abss.vote.service.UserReceptionService;
import com.abss.vote.util.FileUtils;
import com.abss.vote.util.JsonUtil;
import com.abss.vote.util.MPUtils;
import com.abss.vote.util.Utils;
import com.github.pagehelper.PageInfo;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  后台
 */
@Controller
public class UserBackstage {

    @Autowired
    private UserBackstageService userBackstageService;

    @Autowired
    private UserReceptionService userReceptionService;

    @Autowired
    RedisService redisService;

    @Autowired
    private MyProps myProps;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final String APP_ID_B_CLIENT_NEW = "wx08b26b1306ea997b";

    @RequestMapping("/backLogin")
    public String backLogin(Model model){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        String name = mp.getSERVER_NAME();
        model.addAttribute("name",name);
        return "back/login/login";
    }

    @RequestMapping("/record")
    public String record(){
        return "record";
    }


    /**
     * 创建活动
     * @return
     */
    @RequestMapping("/create_activity")
    public String create_activity(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        model.addAttribute("level",ad.getLEVEL());
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        model.addAttribute("isSup",isSup);
        //获取奖项
        List<String> prizes=userBackstageService.getPrizeNames();
        model.addAttribute("prizes",prizes);
        return "back/index/create_activity";
    }

    /**
     * 没有活动创建活动
     * @return
     */
    @RequestMapping("/addactivity")
    public String addactivity(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否最低级管理员
        boolean isSup = userBackstageService.islastAdmin(ad.getID());
        model.addAttribute("isSup",isSup);
        return "back/index/addactivity";
    }

    //账号管理
    @RequestMapping("/account")
    public String account(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        model.addAttribute("isSup",isSup);
        //获取账号等级
        int level = ad.getLEVEL();
        model.addAttribute("level",level);
        int id = ad.getDISTRICT_ID();
        int ads = ad.getDISTRICT_ID();
        model.addAttribute("ads", ads);
        if ("1".equals(isSup)) {
            List<DistrictList> districtLists = userBackstageService.getCounty();// 获取全部地址下级地址
            model.addAttribute("districtLists", districtLists);
        } else {
            // List<DistrictList> districtLists = userBackstageService.getCountys(id);// 获取全部地址下级地址
            List<DistrictList> districtLists = userBackstageService.getCounty();
            model.addAttribute("districtLists", districtLists);
        }
        
        if("1".equals(isSup)){
            return "back/index/Admin_account_management";
        }
        return "back/index/account_management";
    }
    //推荐单位管理
    @RequestMapping("/district")
    public String district(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        int level = ad.getLEVEL();
        model.addAttribute("level",level);
        int ads = ad.getDISTRICT_ID();
        model.addAttribute("ads",ads);
        String isSup = ad.getIS_SUPER_ADMIN();
        model.addAttribute("isSup",isSup);
        if("1".equals(isSup)){//超级管理员
            //获取全部地区的服务器编号，取最后一个加一
            String server_id = userBackstageService.getLastMpInFoServerId();
            model.addAttribute("server_id",server_id);
            model.addAttribute("server",ad.getSERVER_ID());
            return "back/index/supadmin_district_management";
        }
        return "back/index/district_management";
    }


    //推荐单位管理
    @RequestMapping("/districttree")
    public String districttree(Model model, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        //获取是否是超级管理员
        int level = ad.getLEVEL();
        model.addAttribute("level", level);
        String isSup = ad.getIS_SUPER_ADMIN();
        model.addAttribute("isSup", isSup);
        int ads = ad.getDISTRICT_ID();
        model.addAttribute("ads", ads);
        //System.out.println(ads);
        //List<DistrictList> districtLists = userBackstageService.getCounty();//获取全部地址
        //model.addAttribute("districtLists", districtLists);
        return "back/index/district_tree";
    }

    @ResponseBody
    @RequestMapping("/district/tree")
    public List<DistrictList> districtTree(Model model, HttpSession session) {
        List<DistrictList> districtLists = userBackstageService.getCounty();
        return districtLists;
    }

    @RequestMapping("/getProbation")
    public String getProbation() {
        return "back/index/probation";
    }
    
    //获取全部推荐单位
    @ResponseBody
    @RequestMapping("/getAllDistrict")
    public String getAllDistrict(int page,int limit,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        HashMap<String,Object> map = new HashMap<>();
        //获取该管理员的地区id
        int id = ad.getDISTRICT_ID();
        int count  = userBackstageService.getAllDistricts(id);
        List<DistrictList> list = userBackstageService.getAllDistrict(page,limit,id);//获取全部地址
        map.put("code",0);
        map.put("count",count);
        map.put("data",list);
        return JsonUtil.objectToJson(map);
    }

    //获取全部推荐单位
    @ResponseBody
    @RequestMapping("/getAllProbation")
    public String getAllProbation(int page,int limit){
        HashMap<String,Object> map = new HashMap<>();
        PageInfo<Probation> list = userBackstageService.getAllProbation(page,limit);
        map.put("code",0);
        map.put("count",list.getTotal());
        map.put("data",list.getList());
        return JsonUtil.objectToJson(map);
    }



    //获取全部推荐单位
    @ResponseBody
    @RequestMapping("/getAllDistricts")
    public String getAllDistricts(HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        HashMap<String, Object> map = new HashMap<>();
        //获取该管理员的地区id
        int id = ad.getDISTRICT_ID();
        int count = userBackstageService.getAllDistricts(id);
        List<DistrictList> list = userBackstageService.getAllDistrictss(id);//获取全部地址
        map.put("code", 0);
        map.put("count", count);
        map.put("data", list);
        return JsonUtil.objectToJson(map);
    }
    
    // 获取全部推荐单位
    @ResponseBody
    @RequestMapping("/getActivityList")
    public String getActivityList(int page, int limit, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        HashMap<String, Object> map = new HashMap<>();
        //获取该管理员的地区id
        int id = ad.getDISTRICT_ID();
        int count = userBackstageService.getAllDistricts(id);
        List<DistrictList> list = userBackstageService.getAllDistrict(page, limit, id);// 获取全部地址
        map.put("code", 0);
        map.put("count", count);
        map.put("data", list);
        return JsonUtil.objectToJson(map);
    }





    //设置推荐地区是否显示
    @ResponseBody
    @RequestMapping("/updateDisplay")
    public int updateDisplay(Integer ID,String Display){
        return userBackstageService.updateDisplay(ID,Display);
    }

    //作品管理   普通
    @RequestMapping("/work")
    public String work(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        int id = ad.getID();
        model.addAttribute("isSup",isSup);
        boolean flag = userBackstageService.isSubordinate(userBackstageService.getActivityAdminId(ad.getLAST_ACTIVITY_ID()),id);//是否是发布者
        model.addAttribute("flag",flag);
        List<DistrictList> districtLists = userReceptionService.getCountyHaveAdmin();//获取全部地址
        model.addAttribute("districtLists", districtLists);
        String Is_Submit = userBackstageService.getIsSubmit(ad.getLAST_ACTIVITY_ID());
        model.addAttribute("Is_Submit",Is_Submit);
        return "back/index/work_management";
    }
    //作品管理     提交
    @RequestMapping("/works")
    public String works(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        int id = ad.getID();
        model.addAttribute("isSup",isSup);
        boolean flag = userBackstageService.isSubordinate(userBackstageService.getActivityAdminId(ad.getLAST_ACTIVITY_ID()),id);
        model.addAttribute("flag",flag);
        List<DistrictList> districtLists = userReceptionService.getCountyHaveAdmin();//获取全部地址
        model.addAttribute("districtLists", districtLists);
        return "back/index/work_management2";
    }
    //作品管理     提交
    @RequestMapping("/workss")
    public String workss(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        int id = ad.getID();
        model.addAttribute("isSup",isSup);
        boolean flag = userBackstageService.isSubordinate(userBackstageService.getActivityAdminId(ad.getLAST_ACTIVITY_ID()),id);
        model.addAttribute("flag",flag);
        List<DistrictList> districtLists = userReceptionService.getCountyHaveAdmin();//获取全部地址
        model.addAttribute("districtLists", districtLists);
        return "back/index/work_management4";
    }
    //作品管理     设置奖项
    @RequestMapping("/work2")
    public String work2(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        int id = ad.getID();
        model.addAttribute("isSup",isSup);
        boolean flag = userBackstageService.isSubordinate(userBackstageService.getActivityAdminId(ad.getLAST_ACTIVITY_ID()),id);
        model.addAttribute("flag",flag);
        List<DistrictList> districtLists = userReceptionService.getCountyHaveAdmin();//获取全部地址
        model.addAttribute("districtLists", districtLists);
        //查询该活动的奖项信息
        List<Prize> prize = userBackstageService.getPrizeListByActivityId(ad.getLAST_ACTIVITY_ID());
        //System.out.println(prize);
        model.addAttribute("prize",prize);
        return "back/index/work_management3";
    }

    //报名管理
    @RequestMapping("/signup_info")
    public String signup_info(Model model, HttpSession session) {
        return "back/index/signup_info";
    }
    
    @RequestMapping("/evaluate")
    public String evaluate(Model model, HttpSession session) {
        return "back/index/evaluate";
    }

    @ResponseBody
    @RequestMapping("/getUserVotesList")
    public String getUserVotesList(HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        HashMap<String, Object> map = new HashMap<>();
        UserVotesInfo userVotesInfo = new UserVotesInfo();
        userVotesInfo.setACTIVITY_ID(ad.getLAST_ACTIVITY_ID());
        List<UserVotesInfo> list = userBackstageService.getUserVotesList(userVotesInfo);
        map.put("code", 0);
        map.put("data", list);
        return JsonUtil.objectToJson(map);
    }

    /**
     * 删除管理员
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteUserVote")
    public String deleteUserVote(String ID, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int res = userBackstageService.deleteUserVote(ID,ad);
        if (res > 0) {// 有
            return "success";
        }
        return "fail";
    }

    //报名用户
    @RequestMapping("/data_statistics")
    public String data_statistics(){
        return "back/index/user_management";
    }

//管理员
    /**
     * 管理员登录
     * @param ADMIN_ACCOUNT   用户名
     * @param ADMIN_PASSWORD   密码
     * @param session
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public String login(String ADMIN_ACCOUNT,String ADMIN_PASSWORD, HttpSession session,HttpServletRequest request, HttpServletResponse response){
        String res="0";
        Administrators administrators=new Administrators();
        administrators.setADMIN_ACCOUNT(ADMIN_ACCOUNT);
        administrators.setADMIN_PASSWORD(ADMIN_PASSWORD);
        Administrators login =userBackstageService.login(administrators);

        if (login != null) {//登录成功
            // 拿着服务器编号和主账号去查询试用期
            Probation probation = userBackstageService.getProbation(login);
            if (probation.getIS_PROBTATION() == 1) {// 试用期结束
                return "3";
            }
            session.setAttribute("ADMIN_ACCOUNT", login.getADMIN_ACCOUNT());
            int ACTIVITY_ID = login.getLAST_ACTIVITY_ID();//获取最后一次浏览的活动ID
            int result =userBackstageService.checkActivityByid(ACTIVITY_ID);
            if(result==0){//不存在
                List<Activity> activities =null;
                //该管理员是否是超级管理员   超级管理员可以查看所有活动    普通管理员只能查看超级管理员发布的活动和自己服务器上的活动
                if("1".equals(login.getIS_SUPER_ADMIN())) {
                    activities = userBackstageService.getAllActivitiesNoRemove();//查询可查看的活动
                }else{
                    if("100001".equals(login.getSERVER_ID())){//本服务器上的
                        activities = userBackstageService.getAllActivitiesNoRemovess(login.getSERVER_ID(),login.getADMIN());
                    }else{
                        activities = userBackstageService.getAllActivitiesNoRemoves(login.getSERVER_ID());
                    }
                }
                if(activities.size()>0){//说明数据库中有未删除的活动
                    login.setLAST_ACTIVITY_ID(activities.get(0).getACTIVITY_ID());//将最新的活动id填入
                    //将最新的ID填入数据库
                    userBackstageService.setLastActivityId(login.getADMIN_ACCOUNT(),ACTIVITY_ID);

                    res="1";
                }else{//说明数据库中没有可用的活动（没有活动或者全部删除）
                    res="2";//添加活动去
                }
            }else{
                res="1";
            }
        } else {
            res="0";
        }
        session.setAttribute("ADMIN", login);
        return res;
    }

    /**
     * 管理员退出
     * @param session
     * @return
     */
    @RequestMapping("/exit")
    public String exit(HttpSession session){
        if (session != null) {
            session.invalidate();
        }
        return "redirect:/backLogin";
    }

    /**
     * 获取全部管理员
     * @return
     */
    @RequestMapping("/getAllAdmin")
    @ResponseBody
    public Object  getAllAdmin(int page,int limit,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int id = ad.getID();
        HashMap<String,Object> map = new HashMap<>();
        if(limit != 0){
            if(page <= 0) page = 1;
            int count = userBackstageService.getAllAdmins(id);
            List<Administrators> list = userBackstageService.getAllAdmin(id,page,limit);
            map.put("code",0);
            map.put("count",count);
            map.put("data",list);
            return JsonUtil.objectToJson(map);
        }else{
            map.put("msg","参数错误（limit参数错误）！");
        }
        map.put("code",1);
        return JsonUtil.objectToJson(map);
    }



    /**
     * 管理员编辑
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateAdmin")
    public String updateAdmin(Administrators administrators){
        //查看编辑的账号是否是超级管理员（不可编辑）
        Administrators adm = userBackstageService.checkDistrict(administrators);
        if(adm!=null){//有
            Administrators ad = userBackstageService.checkDistrict2(administrators);//根据账号查找
            if(ad.getDISTRICT_ID()!=administrators.getDISTRICT_ID()){
                if(adm.getDISTRICT_ID()==administrators.getDISTRICT_ID()){//已有该地区管理员
                    return "haveDistrict";
                }
            }
        }
        userBackstageService.updateAdmin(administrators);
        return "success";
    }


    /**
     * 添加管理员
     * @return
     */
    @ResponseBody
    @RequestMapping("/addAdmin")
    public String addAdmin(Administrators administrators,HttpSession session){
        Administrators adm = userBackstageService.checkDistrict(administrators);
        if(adm!=null){//有
                return "haveDistrict";
        }
        int res2 = userBackstageService.checkUserName(administrators);
        if(res2>0){//该账号已有
            return "haveUserName";
        }
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int level = ad.getLEVEL();//获取等级
        int id =ad.getID();//获取id
        String isSup = ad.getIS_SUPER_ADMIN();
        administrators.setIS_SUPER_ADMIN(isSup);
        if("1".equals(isSup)){//超级管理员添加，获取地区的服务器编号
            administrators.setSERVER_ID(userBackstageService.getServerId(administrators.getDISTRICT_ID()));
        }else{
            administrators.setSERVER_ID(ad.getSERVER_ID());
        }
        boolean falg = false;
        if(ad.getSERVER_ID().equals(administrators.getSERVER_ID())){
            falg=true;
        }
        userBackstageService.addAdmin(administrators,id,level,falg,ad);
        return "success";
    }

    /**
     * 添加推荐单位超级管理员
     * @param DISTRICT_NAME
     * @return
     */
    @ResponseBody
    @RequestMapping("/addDistrictAdmin")
    public int addDistrictAdmin(String DISTRICT_NAME, String PROVINCE, String CITY, Integer DATA_LEVEL, String SERVER_ID,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取该管理员的地址id
        int id= ad.getDISTRICT_ID();
        String name =ad.getADMIN_NAME();
        String admin = ad.getADMIN();//超级管理员添加地址时，此时admin是超级管理员的，需要在添加账号的时候在修改
        return userBackstageService.checkDistrictNameAdmin(DISTRICT_NAME,PROVINCE,CITY,DATA_LEVEL,SERVER_ID,id,name,admin);
    }

    /**
     * 添加推荐单位
     * @param DISTRICT_NAME
     * @return
     */
    @ResponseBody
    @RequestMapping("/addDistrict")
    public int addDistrict(String DISTRICT_NAME, String PROVINCE, String CITY, Integer DATA_LEVEL, HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取该管理员的地址id
        int id= ad.getDISTRICT_ID();
        String name =ad.getADMIN_NAME();
        String server_id = ad.getSERVER_ID();
        String admin = ad.getADMIN();
        return userBackstageService.checkDistrictNameAdmin(DISTRICT_NAME, PROVINCE, CITY, DATA_LEVEL,server_id,id,name,admin);
    }

    /**
     * 修改推荐单位
     * @param ID
     * @param DISTRICT_NAME
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateDistrict")
    public int updateDistrict(Integer ID,String DISTRICT_NAME,String PROVINCE, String CITY, Integer DATA_LEVEL){
        return userBackstageService.updateDistrict(ID,DISTRICT_NAME,PROVINCE, CITY, DATA_LEVEL);
    }

    /**
     * 删除推荐单位
     * @param ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteDistrict")
    public String deleteDistrict(Integer ID,HttpSession session){
        //System.out.println(ID);
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        Administrators isSup = userBackstageService.getAdminById(ID);//查看该地区是否是超级管理员所在
        if(isSup!=null){
            if("1".equals(isSup.getIS_SUPER_ADMIN())){//是超级管理员   不可删除
                return "chaoji";
            }
        }
        int res = userBackstageService.deleteDistrict(ID,ad);
        if(res>0){//有
            return "success";
        }
        return "fail";
    }

    /**
     * 删除管理员
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteAdmin")
    public String deleteAdmin(String ADMIN_ACCOUNT,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        Administrators isSup = userBackstageService.getAdminByAccount(ADMIN_ACCOUNT);
        if("1".equals(isSup.getIS_SUPER_ADMIN())){//是超级管理员   不可删除
            return "chaoji";
        }
        int res = userBackstageService.deleteAdmin(ADMIN_ACCOUNT,ad);
        if(res>0){//有
            return "success";
        }
        return "fail";
    }

//首页

    @RequestMapping("/toIndex")
    public String toIndex(HttpSession session,Model model){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        if(ad==null){
            return "redirect:/backLogin";
        }
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        Activity activity = userBackstageService.getActivityId(ACTIVITY_ID);
        model.addAttribute("activity",activity);
        //获取logo和管理员头像
        Logo logo = userBackstageService.getLogo(ad);
        model.addAttribute("logo",logo);
        String name = mp.getSERVER_NAME();
        model.addAttribute("name",name);
        return "index";
    }

    /**
     * 获取首页内容
     * @param model
     * @return
     */
    @RequestMapping("/getIndexAll")
    public String getIndexAll(HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        Activity activity = userBackstageService.getActivityId(ACTIVITY_ID);
        model.addAttribute("activity",activity);
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        boolean flag = userBackstageService.isSubordinate(activity.getADMIN_ID(),ad.getID());
        //获取地址ID
        int DISTRICT_ID=ad.getDISTRICT_ID();
        // int ParticipantsCount = userBackstageService.getParticipantsCount(ACTIVITY_ID, isSup, DISTRICT_ID, flag);//获取参加该活动人数
        List<Integer> districtIdList = new ArrayList<>();
        if (!"1".equals(ad.getIS_SUPER_ADMIN()) || !ad.getID().equals(activity.getADMIN_ID())) {
            Integer districtId = ad.getDISTRICT_ID();
            districtIdList.add(districtId);
            getChildrenIds(districtId, districtIdList);
        }
        String districtIds = districtIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
        int participantsCount = 0;
        if (ad.getIS_SUPER_ADMIN().equals("1") || ad.getID().equals(activity.getADMIN_ID())) {
            String regTotal = "select count(1) from USER_REG_INFO where ACTIVITY_ID=?";
            participantsCount = jdbcTemplate.queryForObject(regTotal, new Object[] { ACTIVITY_ID }, Integer.class);
        } else {
            String regTotal = "select count(1) from USER_REG_INFO u left join DISTRICT_LIST d on u.COMPANY=d.SCHOOL_ID where u.ACTIVITY_ID=? and d.ID in ("+ districtIds + ")";
            participantsCount = jdbcTemplate.queryForObject(regTotal, new Object[] { ACTIVITY_ID }, Integer.class);
        }
        model.addAttribute("ParticipantsCount", participantsCount);
        int WorksCount = userBackstageService.getWorksCount(ACTIVITY_ID,isSup,DISTRICT_ID,flag);//获取该活动作品数
        model.addAttribute("WorksCount",WorksCount);
        List<UserWorkVo> works = userBackstageService.getWorks(ACTIVITY_ID,isSup,DISTRICT_ID,flag);//获取该活动下14个作品
        model.addAttribute("works",works);
        return "back/index/index";//到首页
    }

    /**
     * 获取首页内容
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/getIndexAl")
    public Activity getIndexAl(int ACTIVITY_ID,HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //将该ACTIVITY_ID存入数据库
        userBackstageService.setLastActivityId(ad.getADMIN_ACCOUNT(),ACTIVITY_ID);
        //替换session
        Administrators login =userBackstageService.getlogin(ad.getADMIN_ACCOUNT());
        session.setAttribute("ADMIN", login);
        return userBackstageService.getActivityId(ACTIVITY_ID);
    }

//活动



    /**
     * 分页查询所有的活动
     * @param model
     * @return
     */
    @RequestMapping("/getAllActivity")
    public String getAllActivity(@RequestParam(required=false,defaultValue="1") int page,
                                @RequestParam(required=false,defaultValue="10")int limit,
                                Model model,String name ,String state,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        String isSup = ad.getIS_SUPER_ADMIN();
        PageInfo<Activity> allActivity= userBackstageService.getActivityByStateAndName(name, state, page, limit, ad);
        model.addAttribute("admin_id",ad.getID());
        model.addAttribute("isSup",isSup);
        model.addAttribute("level",ad.getLEVEL());
        model.addAttribute("name",name);
        model.addAttribute("state",state);
        model.addAttribute("allActivity",allActivity);
        return "back/index/activity_management";//活动列表页
    }

    /**
     * 删除活动
     * @param ACTIVITY_ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteActivity")
    public int deleteActivity(String ACTIVITY_ID){
        //根据id删除活动
        redisService.deleteActivity(Integer.parseInt(ACTIVITY_ID));
        return userBackstageService.deleteActivity(ACTIVITY_ID);
    }


    /**
     * 创建活动
     * @return
     */
    @ResponseBody
    @RequestMapping("/addActivity")
    public int addActivity(@RequestBody Activity activity,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());

        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_WIN=0;

        if (activity.getPrizeInfos() != null && activity.getPrizeInfos().size() != 0) {
            for (int i = 0; i < activity.getPrizeInfos().size(); i++) {
                Prize prize = activity.getPrizeInfos().get(i);
                ACTIVITY_WIN += prize.getPRIZE_USERNUMBER();
            }
        }
        
        activity.setACTIVITY_WIN(ACTIVITY_WIN);
        activity.setADMIN_ACCOUNT(ad.getADMIN_ACCOUNT());
        activity.setADMIN_NAME(ad.getADMIN_NAME());
        activity.setADMIN_ID(ad.getID());
        activity.setSERVER_ID(ad.getSERVER_ID());
        activity.setADMIN(ad.getADMIN());
        int res = userBackstageService.addActivity(activity, mp);
        
        if (activity.getPrizeInfos() != null && activity.getPrizeInfos().size() != 0) {
            for (int i = 0; i < activity.getPrizeInfos().size(); i++) {
                Prize prize = activity.getPrizeInfos().get(i);
                prize.setACTIVITY_ID(activity.getACTIVITY_ID());
                userBackstageService.addPrize(prize);
            }
        }
        
        if (activity.getGroupRuleInfos() != null && activity.getGroupRuleInfos().size() != 0) {
            for (int i = 0; i < activity.getGroupRuleInfos().size(); i++) {
                GroupRule groupRule = activity.getGroupRuleInfos().get(i);
                groupRule.setACTIVITY_ID(activity.getACTIVITY_ID());
                groupRule.setGROUP_RULE_TYPE(activity.getGROUP_RULE_TYPE());
                userBackstageService.addGroupRule(groupRule);
            }
        }
        
        String bizCode = userBackstageService.getDistrictBizById(ad.getDISTRICT_ID());
        String sql = "select * from [classificationofreading].[dbo].[mp_info] where mp_app_id=?";
        Map<String, Object> mpInfoMap = jdbcTemplate.queryForMap(sql, APP_ID_B_CLIENT_NEW);
        String accessToken = mpInfoMap.get("ACCESS_TOKEN")+"";
        String qrcode = MPUtils.getActivityQRCode(activity.getACTIVITY_ID() + "", bizCode, accessToken);
        activity.setACTIVITY_CODE(qrcode);
        userBackstageService.updateQrcode(activity);

        //活动
        redisService.addActivity(activity.getACTIVITY_ID());
        return  res;
    }

    @ResponseBody
    @RequestMapping("/updateTime")
    public int updateTime(Activity activity, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        return userBackstageService.updateTime(activity);
    }
    
    @ResponseBody
    @RequestMapping("/setEntryTime")
    public int setEntryTime(Activity activity, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        return userBackstageService.setEntryTime(activity);
    }

    /**
     * 修改奖品
     * @return
     */
    @ResponseBody
    @RequestMapping("/updatePrize")
    public int updatePrize(@RequestBody List<Prize> prizes,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        int ACTIVITY_WIN=0;
        int ret=0;
        for(int i=0;i<prizes.size();i++){
            Prize prize=prizes.get(i);
            prize.setACTIVITY_ID(ACTIVITY_ID);
            ret+=userBackstageService.addPrize(prize);
            ACTIVITY_WIN+=prize.getPRIZE_USERNUMBER();
        }
        Activity Activity = userBackstageService.getNumber(ACTIVITY_ID);
        if(Activity.getACTIVITY_WIN()!=null) {
            ACTIVITY_WIN += Activity.getACTIVITY_WIN();
        }

        userBackstageService.setACTIVITY_WIN(ACTIVITY_ID,ACTIVITY_WIN);

        return ret;
    }

    /**
     * 上传活动封面图片
     * @param file
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/UploadImg")
    public String UploadImg(MultipartFile file, Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        String serverId= ad.getSERVER_ID();
        String ACTIVITY_IMG ="";
        long time= Utils.getName();//获取当前时间戳
        String fileName = file.getOriginalFilename();//获取原文件名
        ACTIVITY_IMG = "/activity/"+time+ fileName.substring(fileName.indexOf("."));
        File dest = new File(Utils.getFilePath(serverId).getFILE_PATH() + ACTIVITY_IMG);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("ACTIVITY_IMG",ACTIVITY_IMG);
        return "";
    }


    @ResponseBody
    @RequestMapping("/operate/uploadImg")
    public String operate_UploadImg(MultipartFile file,String dir,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        String PRIZE_GOODS_IMG ="";
        long time= Utils.getName();//获取当前时间戳
        String fileName = file.getOriginalFilename();//获取原文件名
        PRIZE_GOODS_IMG = "/"+dir+"/"+time+ fileName.substring(fileName.indexOf("."));
        File dest = new File(mp.getFILE_PATH() + PRIZE_GOODS_IMG);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mp.getDOMAIN_NAME()+PRIZE_GOODS_IMG;
    }
    /**
     * 编辑活动回显
     * @param ACTIVITY_ID
     * @param model
     * @return
     */
    @RequestMapping("/changeActivityById")
    public String changeActivityById(int ACTIVITY_ID,Model model){
        Activity activity =userBackstageService.getActivityById(ACTIVITY_ID);
        model.addAttribute("activity",activity);
        return "";//修改页面
    }

    /**
     * 修改活动
     * @param activity
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateActivityById")
    public int updateActivityById(Activity activity, HttpSession session) {
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        int res = userBackstageService.updateActivityById(activity, mp);
        return res;
    }
    
    @ResponseBody
    @RequestMapping("/updateActivityDetailsById")
    public int updateActivityDetailsById(Activity activity, HttpSession session) {
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        int res = userBackstageService.updateActivityDetailsById(activity, mp);
        return res;
    }
    /**
     * 修改活动
     * @param activity
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateAc")
    public String updateAc(Activity activity,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        int res = userBackstageService.updateAc(activity,mp);
        if(res>0) {
            return "success";
        }
        return "fail";
    }

    /**
     * 获取活动详情
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/getActivityDetails")
    public String getActivityDetails(HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        model.addAttribute("isSup",isSup);
        int ADMIN_ID = ad.getID();
        model.addAttribute("admin_id",ADMIN_ID);
        ActivityPrizeVo ap = userBackstageService.getActivityDetails(ACTIVITY_ID);
        List<Prize> prizeList = userBackstageService.getPrizeListByActivityId(ACTIVITY_ID);
        List<GroupRule> groupRuleList = userBackstageService.getGroupRuleListByActivityId(ACTIVITY_ID);
        //TODO 修改前端
        model.addAttribute("prizeList", prizeList);
        model.addAttribute("groupRuleList", groupRuleList);

        ap.setACTIVITY_DETAILS(Utils.getHtml(ap.getACTIVITY_DETAILS()));
        model.addAttribute("ActivityDetails",ap);
        return "back/index/activity_details";
    }

//奖项

    /**
     * 上传奖品图片
     * @param file
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/UploadPrize")
    public String UploadPrize(MultipartFile file, Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        String serverId= ad.getSERVER_ID();
        String PRIZE_GOODS_IMG ="";
        long time= Utils.getName();//获取当前时间戳
        String fileName = file.getOriginalFilename();//获取原文件名
        PRIZE_GOODS_IMG = "/prize/"+time+ fileName.substring(fileName.indexOf("."));
        File dest = new File(Utils.getFilePath(serverId).getFILE_PATH() + PRIZE_GOODS_IMG);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("ACTIVITY_IMG",PRIZE_GOODS_IMG);
        return "";
    }


    /**
     * 添加奖项
     * @param prize
     * @return
     */
    @RequestMapping("/addPrize")
    public String addPrize(Prize prize){
        userBackstageService.addPrize(prize);
        return "redirect:/getAllPrize";//跳转奖项列表页
    }

    /**
     * 获取全部奖项列表
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/getAllPrize")
    public String getAllPrize(@RequestParam(required=false,defaultValue="1") int pageNum,
                              @RequestParam(required=false,defaultValue="15")int pageSize,
                              Model model){
        PageInfo<Prize> prize=userBackstageService.getAllPrize(pageNum,pageSize);
        model.addAttribute("prize",prize);
        return "";//跳转奖项列表页
    }

//作品

    /**
     * 获取该活动下所有作品
     * @param page
     * @param limit
     * @param DISTRICT_ID  超级管理员时 选择的地区
     * @param AUDIT_STATE  普通管理员时 选择的作品状态
     * @param IS_LOCAL     发布者时    选择的是否是本地区
     * @param WORK_NAME
     * @param session
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/getWorkByActivityId")
    public Object  getWorkByActivityId(int page,int limit,Integer DISTRICT_ID,Integer AUDIT_STATE,Integer IS_LOCAL,String WORK_NAME,HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        //获取地址ID
        int districtId=ad.getDISTRICT_ID();
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        if(DISTRICT_ID==null)DISTRICT_ID=-1;
        if(AUDIT_STATE==null)AUDIT_STATE=-1;
        if(IS_LOCAL==null)IS_LOCAL=0;
        HashMap<String,Object> map = new HashMap<>();
        if(limit != 0){
            if(page <= 0) page = 1;
            PageInfo<UserWorkVo> list = userBackstageService.getWorkByActivityId(page,limit,DISTRICT_ID,IS_LOCAL,AUDIT_STATE,WORK_NAME,ACTIVITY_ID,isSup,districtId);
            map.put("code",0);
            map.put("count",list.getTotal());
            map.put("data",list.getList());
            map.put("IS_LOCAL",IS_LOCAL);
            return JsonUtil.objectToJson(map);
        }else{
            map.put("msg","参数错误（limit参数错误）！");
        }
        map.put("code",1);
        return JsonUtil.objectToJson(map);
    }
    /**
     * 获取该活动下所有作品
     * @param page
     * @param limit
     * @param DISTRICT_ID  超级管理员时 选择的地区
     * @param AUDIT_STATE  普通管理员时 选择的作品状态
     * @param IS_LOCAL     发布者时    选择的是否是本地区
     * @param WORK_NAME
     * @param session
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/getWorkByActivityIds")
    public Object  getWorkByActivityIds(int page,int limit,Integer DISTRICT_ID,Integer AUDIT_STATE,Integer IS_LOCAL,String WORK_NAME,HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        //获取地址ID
        int districtId=ad.getDISTRICT_ID();
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        if(DISTRICT_ID==null)DISTRICT_ID=-1;
        if(AUDIT_STATE==null)AUDIT_STATE=-1;
        if(IS_LOCAL==null)IS_LOCAL=0;
        HashMap<String,Object> map = new HashMap<>();
        if(limit != 0){
            if(page <= 0) page = 1;
            PageInfo<UserWorkVo> list = userBackstageService.getWorkByActivityIds(page,limit,DISTRICT_ID,IS_LOCAL,AUDIT_STATE,WORK_NAME,ACTIVITY_ID,isSup,districtId);
            map.put("code",0);
            map.put("count",list.getTotal());
            map.put("data",list.getList());
            map.put("IS_LOCAL",IS_LOCAL);
            return JsonUtil.objectToJson(map);
        }else{
            map.put("msg","参数错误（limit参数错误）！");
        }
        map.put("code",1);
        return JsonUtil.objectToJson(map);
    }
    /**
     * 获取该活动下所有作品
     * @param page
     * @param limit
     * @param DISTRICT_ID  超级管理员时 选择的地区
     * @param AUDIT_STATE  普通管理员时 选择的作品状态
     * @param IS_LOCAL     发布者时    选择的是否是本地区
     * @param WORK_NAME
     * @param session
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/getWorkByActivityIdss")
    public Object  getWorkByActivityIdss(int page,int limit,Integer DISTRICT_ID,Integer AUDIT_STATE,Integer IS_LOCAL,String WORK_NAME,HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        //获取地址ID
        int districtId=ad.getDISTRICT_ID();
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        if(DISTRICT_ID==null)DISTRICT_ID=-1;
        if(AUDIT_STATE==null)AUDIT_STATE=-1;
        if(IS_LOCAL==null)IS_LOCAL=0;
        HashMap<String,Object> map = new HashMap<>();
        if(limit != 0){
            if(page <= 0) page = 1;
            PageInfo<UserWorkVo> list = userBackstageService.getWorkByActivityIdss(page,limit,DISTRICT_ID,IS_LOCAL,AUDIT_STATE,WORK_NAME,ACTIVITY_ID,isSup,districtId);
            //查询该活动的奖项信息
            List<Prize> prize = userBackstageService.getPrizeListByActivityId(ad.getLAST_ACTIVITY_ID());
            map.put("code",0);
            map.put("count",list.getTotal());
            map.put("data",list.getList());
            map.put("prizes",prize);
            map.put("IS_LOCAL",IS_LOCAL);
            return JsonUtil.objectToJson(map);
        }else{
            map.put("msg","参数错误（limit参数错误）！");
        }
        map.put("code",1);
        return JsonUtil.objectToJson(map);
    }

    /**
     * 获取该活动下所有作品
     * @param page
     * @param limit
     * @param DISTRICT_ID  超级管理员时 选择的地区
     * @param AUDIT_STATE  普通管理员时 选择的作品状态
     * @param IS_LOCAL     发布者时    选择的是否是本地区
     * @param WORK_NAME
     * @param session
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/getWorkByActivityIdsss")
    public Object  getWorkByActivityIdsss(int page,int limit,Integer DISTRICT_ID,Integer AUDIT_STATE,Integer IS_LOCAL,String WORK_NAME,HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        //获取地址ID
        int districtId=ad.getDISTRICT_ID();
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        if(DISTRICT_ID==null)DISTRICT_ID=-1;
        if(AUDIT_STATE==null)AUDIT_STATE=-1;
        if(IS_LOCAL==null)IS_LOCAL=0;
        HashMap<String,Object> map = new HashMap<>();
        if(limit != 0){
            if(page <= 0) page = 1;
            PageInfo<UserWorkVo> list = userBackstageService.getWorkByActivityIdsss(page,limit,DISTRICT_ID,IS_LOCAL,AUDIT_STATE,WORK_NAME,ACTIVITY_ID,isSup,districtId);
            //查询该活动的奖项信息
            List<Prize> prize = userBackstageService.getPrizeListByActivityId(ad.getLAST_ACTIVITY_ID());
            map.put("code",0);
            map.put("count",list.getTotal());
            map.put("data",list.getList());
            map.put("prizes",prize);
            map.put("IS_LOCAL",IS_LOCAL);
            return JsonUtil.objectToJson(map);
        }else{
            map.put("msg","参数错误（limit参数错误）！");
        }
        map.put("code",1);
        return JsonUtil.objectToJson(map);
    }

    /**
     * 根据作品ID获取作品详情
     * @return
     */
    @RequestMapping("/getWork")
    public String getWork(int ID, Model model){
        UserWorkVo userWorkVo = userBackstageService.getWork(ID);
        model.addAttribute("userWorkVo",userWorkVo);
        if(userWorkVo.getWORK_TYPE().equals("1")){
            return "";// 1 音频页
        }
        return "";//0 视频页
    }

    /**
     * 删除作品
     * @param WORK_ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/delWork")
    public int delWork(int WORK_ID){
        return userBackstageService.delWork(WORK_ID);
    }



    /**
     * 审核作品
     * @param AUDIT_STATE
     * @param WORK_ID
     * @param COMMENT
     * @return
     */
    @ResponseBody
    @RequestMapping("/audit")
    public int audit(int AUDIT_STATE, int WORK_ID,String COMMENT){
        int res = userBackstageService.audit(AUDIT_STATE,WORK_ID,COMMENT);
        return res;
    }

//用户管理

    /**
     * 获取全部报名列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUserRegInfo")
    public String getUserRegInfo(int page, int limit, String USER_NAME, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        HashMap<String, Object> map = new HashMap<>();
        if (limit != 0) {
            if (page <= 0)
                page = 1;
            PageInfo<DistrictListUserWorkVo> list = userBackstageService.getUserRegInfo(page, limit, USER_NAME, ad);
            map.put("code", 0);
            map.put("count", list.getTotal());
            map.put("data", list.getList());
            return JsonUtil.objectToJson(map);
        } else {
            map.put("msg", "参数错误（limit参数错误）！");
        }
        map.put("code", 1);
        return JsonUtil.objectToJson(map);
    }
    
    @ResponseBody
    @RequestMapping("/getAllUserRegInfo")
    public String getAllUserRegInfo(String USER_NAME,HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        HashMap<String, Object> map = new HashMap<>();
        List<DistrictListUserWorkVo> list = userBackstageService.getAllUserRegInfo(USER_NAME,ad);
        map.put("code", 0);
        map.put("data", list);
        return JsonUtil.objectToJson(map);
    }

    /**
     * 获取全部用户列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUser")
    public String getUser(int page,int limit,String USER_NAME,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        HashMap<String,Object> map = new HashMap<>();
        if(limit != 0){
            if(page <= 0) page = 1;
            PageInfo<User> list=userBackstageService.getUser(page,limit,USER_NAME,ad);
            map.put("code",0);
            map.put("count",list.getTotal());
            map.put("data",list.getList());
            return JsonUtil.objectToJson(map);
        }else{
            map.put("msg","参数错误（limit参数错误）！");
        }
        map.put("code",1);
        return JsonUtil.objectToJson(map);
    }


    /**
     * 获取全部用户列表
     * @return
     */
    @RequestMapping("/getUsers")
    public String getUsers(Model model){
        List<String> list=userBackstageService.getUsers();
        model.addAttribute("user",list);
        return "front_bak/active";
    }

    //活动详情
    @RequestMapping("/activity_details")
    public String activity_details(HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        Activity activity = userBackstageService.getActivityId(ACTIVITY_ID);
        model.addAttribute("activity",activity);
        return "back/index/activity_details";
    }

    /**
     * 提交作品到超级管理员
     * @param WORK_ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/setWork")
    public int setWork(int WORK_ID,HttpSession session) {
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        return userBackstageService.setWork(WORK_ID,ad);
    }

    /**
     * 取消提交作品到超级管理员
     * @param WORK_ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/deWork")
    public int deWork(int WORK_ID) {
        return userBackstageService.deWork(WORK_ID);
    }

    /**
     * 超级管理员筛选决赛作品
     * @param WORK_ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/promotionWork")
    public int setWpromotionWorkork(int WORK_ID) {
        return userBackstageService.promotionWork(WORK_ID);
    }

    /**
     * 超级管理员取消决赛作品
     * @param WORK_ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/depromotionWork")
    public int deWpromotionWorkork(int WORK_ID) {
        return userBackstageService.deWpromotionWorkork(WORK_ID);
    }

    /**
     * 创建作品
     * @param model
     * @return
     */
    @RequestMapping("/createWork")
    public String createWork(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        String isSup = ad.getIS_SUPER_ADMIN();
        model.addAttribute("isSup",isSup);
        //获取活动ID
        //查询该活动下的发布者id
        //查询是否是下属单位
        int id = ad.getID();
        boolean flag = userBackstageService.isSubordinates(userBackstageService.getActivityAdminId(ad.getLAST_ACTIVITY_ID()),id);
        model.addAttribute("id",id);
        model.addAttribute("flag",flag);
        model.addAttribute("dis_name",userBackstageService.getDisName(ad.getDISTRICT_ID()));
        model.addAttribute("dis_id",ad.getDISTRICT_ID());
        Activity ac = userBackstageService.getActivityId(ad.getLAST_ACTIVITY_ID());
        model.addAttribute("ac_name",ac.getACTIVITY_NAME());
        model.addAttribute("ac_id",ac.getACTIVITY_ID());
        return "back/index/create_works";
    }

    /**
     * 后台创建作品上传封面图
     * @param file1
     * @return
     */
    @ResponseBody
    @RequestMapping("/picUpload")
    public Map<String,Object> picUpload(@RequestParam(value = "file1", required = false) MultipartFile file1,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Map<String,Object> ret=new HashMap<>();
        String Picture ="";
        String picName ="";
        if (file1.isEmpty()) {
            ret.put("code",0);
            return ret;
        }
        long time1=Utils.getName();//获取当前时间戳
        String fileName1 = file1.getOriginalFilename();//获取原文件名
        Picture = "/copy/"+time1+ fileName1.substring(fileName1.indexOf("."));
        String name = time1+ fileName1.substring(fileName1.indexOf("."));
        File dest1 = new File(mp.getFILE_PATH() + Picture);
        try {
            file1.transferTo(dest1);
            picName = FileUtils.saveImage(dest1,name,mp);
            ret.put("code",1);
            ret.put("pic",picName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 后台上传音频
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping("/soundUpload")
    public Map<String,Object> soundUpload(@RequestParam(value = "file", required = false) MultipartFile file,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Map<String,Object> ret=new HashMap<>();
        Encoder encoder = new Encoder();
        String Sound ="";
        if (file.isEmpty()) {
            ret.put("code",0);
            ret.put("msg","作品为空，请上传作品！");
            return ret;
        }
        if(file.getSize()>(200*1024*1024)){
            ret.put("code",0);
            ret.put("msg","请上传200M以内的作品！");
            return ret;
        }
        long ms = 0;
        long time2=Utils.getName();//获取当前时间戳
        String fileName2 = file.getOriginalFilename();//获取原文件名
        Sound = "/sound/"+time2+( fileName2.indexOf(".")==-1?"":fileName2.substring(fileName2.indexOf(".")));
        File dest2 = new File(mp.getFILE_PATH() + Sound);
        try {
            file.transferTo(dest2);
            MultimediaInfo m = encoder.getInfo(dest2);
            ms = m.getDuration();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int ss = 1000;
        Integer time=(int)(ms/ss) ;
        ret.put("name",mp.getDOMAIN_NAME()+Sound);
        ret.put("time",time);
        return ret;
    }

    /**
     * 后台上传视频
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping("/VideoUpload")
    public Map<String,Object> VideoUpload(@RequestParam(value = "file", required = false) MultipartFile file,HttpSession session){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Map<String,Object> ret=new HashMap<>();
        Encoder encoder = new Encoder();
        String Sound ="";
        if (file.isEmpty()) {
            ret.put("code",0);
            ret.put("msg","作品为空，请上传作品！");
            return ret;
        }
        if(file.getSize()>(200*1024*1024)){
            ret.put("code",0);
            ret.put("msg","请上传200M以内的作品！");
            return ret;
        }
        long ms = 0;
        long time2=Utils.getName();//获取当前时间戳
        String fileName2 = file.getOriginalFilename();//获取原文件名
        Sound = "/video/"+time2+( fileName2.indexOf(".")==-1?"":fileName2.substring(fileName2.indexOf(".")));
        File dest2 = new File(mp.getFILE_PATH() + Sound);
        try {
            file.transferTo(dest2);
            MultimediaInfo m = encoder.getInfo(dest2);
            ms = m.getDuration();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int ss = 1000;
        Integer time=(int)(ms/ss) ;
        ret.put("name",mp.getDOMAIN_NAME()+Sound);
        ret.put("time",time);
            return ret;
    }

    /**
     * 后台上传作品
     * @param userWorkVo
     * @return
     */
    @ResponseBody
    @RequestMapping("/backUploadWork")
    public int backUploadWork(UserWorkVo userWorkVo,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        userWorkVo.setDISTRICT_ID(ad.getDISTRICT_ID());
        return userBackstageService.backUploadWork(userWorkVo);
    }

    /**
     * 地区详情
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/accountWorkDetails")
    public String accountWorkDetails(HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        //改版新    将redis中的活动信息写入数据库
        //redisService.setActivityDetailFromRedisToSqlServer(ACTIVITY_ID);
        //改版新    将redis中的作品信息写入数据库
        //redisService.setWorkDetailFromRedisToSqlServer(ACTIVITY_ID);
        //获取当前活动名称
        Activity activity = userBackstageService.getActivityId(ACTIVITY_ID);
        model.addAttribute("activityId", ACTIVITY_ID);
        model.addAttribute("activityName", activity.getACTIVITY_NAME());//活动名称
        model.addAttribute("STAGE_1ST_STARTTIME", activity.getST1_STARTTIME());
        model.addAttribute("STAGE_1ST_ENDTIME", activity.getST1_ENDTIME());
        model.addAttribute("STAGE_2ND_STARTTIME", activity.getST2_STARTTIME());
        model.addAttribute("STAGE_2ND_ENDTIME", activity.getST2_ENDTIME());
        model.addAttribute("STAGE_3RD_STARTTIME", activity.getST3_STARTTIME());
        model.addAttribute("STAGE_3RD_ENDTIME", activity.getST3_ENDTIME());
        // int participantsCount = redisService.getREG_USER(ACTIVITY_ID);
        List<Integer> districtIdList = new ArrayList<>();
        if (!"1".equals(ad.getIS_SUPER_ADMIN()) || !ad.getID().equals(activity.getADMIN_ID())) {
            Integer districtId = ad.getDISTRICT_ID();
            districtIdList.add(districtId);
            getChildrenIds(districtId, districtIdList);
        }
        String districtIds = districtIdList.stream().map(String::valueOf).collect(Collectors.joining(","));

        int participantsCount = 0;
        int participantsTestCount = 0;
        int maleCount = 0;
        int femaleCount = 0;
        int csTotal = 0;
        int fsTotal = 0;
        int fsFTotal = 0;
        int jsTotal = 0;
        int jsFTotal = 0;
        int testCount = 0;
        if (ad.getIS_SUPER_ADMIN().equals("1") || ad.getID().equals(activity.getADMIN_ID())) {
            String regTotal = "select count(1) from USER_REG_INFO where ACTIVITY_ID=?";
            participantsCount = jdbcTemplate.queryForObject(regTotal, new Object[] { ACTIVITY_ID }, Integer.class);
            String regTestTotal = "select count(1) from USER_REG_INFO where ACTIVITY_ID=? and CUR_STATUS<>?";
            participantsTestCount = jdbcTemplate.queryForObject(regTestTotal, new Object[] { ACTIVITY_ID, "0" },
                    Integer.class);
            String sexSQL = "select count(1) from USER_REG_INFO where ACTIVITY_ID=? and APPRAISAL_USER_ID in (select appraisal_user_id from [classificationofreading].[dbo].[abss_appraisal_user] where gender=?)";
            maleCount = jdbcTemplate.queryForObject(sexSQL, new Object[] { ACTIVITY_ID, 1 }, Integer.class);
            femaleCount = jdbcTemplate.queryForObject(sexSQL, new Object[] { ACTIVITY_ID, 2 }, Integer.class);
            String competitionSQL = "select count(1) from USER_REG_INFO where ACTIVITY_ID=? and CUR_STATUS=?";
            csTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "1" }, Integer.class);
            fsTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "2" }, Integer.class);
            fsFTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "3" },
                    Integer.class);
            jsTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "4" }, Integer.class);
            jsFTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "5" },
                    Integer.class);

            String testSQL = "select count(1) from ACTIVITY_APPRAISAL_TAG where ACTIVITY_ID=?";
            testCount = jdbcTemplate.queryForObject(testSQL, new Object[] { ACTIVITY_ID }, Integer.class);
        } else {
            String regTotal = "select count(1) from USER_REG_INFO u left join DISTRICT_LIST d on u.COMPANY=d.SCHOOL_ID where u.ACTIVITY_ID=? and d.ID in ("+ districtIds+")";
            participantsCount = jdbcTemplate.queryForObject(regTotal, new Object[] { ACTIVITY_ID }, Integer.class);

            String regTestTotal = "select count(1) from USER_REG_INFO u left join DISTRICT_LIST d on u.COMPANY=d.SCHOOL_ID where u.ACTIVITY_ID=? and u.CUR_STATUS<>? and d.ID in ("+ districtIds+")";
            participantsTestCount = jdbcTemplate.queryForObject(regTestTotal, new Object[] { ACTIVITY_ID, "0" },
                    Integer.class);
            String sexSQL = "select count(1) from USER_REG_INFO u left join DISTRICT_LIST d on u.COMPANY=d.SCHOOL_ID where u.ACTIVITY_ID=? and d.ID in ("+ districtIds+") and u.APPRAISAL_USER_ID in (select appraisal_user_id from [classificationofreading].[dbo].[abss_appraisal_user] where gender=?)";
            maleCount = jdbcTemplate.queryForObject(sexSQL, new Object[] { ACTIVITY_ID, 1 }, Integer.class);
            femaleCount = jdbcTemplate.queryForObject(sexSQL, new Object[] { ACTIVITY_ID, 2 }, Integer.class);
            String competitionSQL = "select count(1) from USER_REG_INFO u left join DISTRICT_LIST d on u.COMPANY=d.SCHOOL_ID where u.ACTIVITY_ID=? and u.CUR_STATUS=? and d.ID in ("+ districtIds+")";
            csTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "1" }, Integer.class);
            fsTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "2" }, Integer.class);
            fsFTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "3" },
                    Integer.class);
            jsTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "4" }, Integer.class);
            jsFTotal = jdbcTemplate.queryForObject(competitionSQL, new Object[] { ACTIVITY_ID, "5" },
                    Integer.class);
            String testSQL = "select count(1) from ACTIVITY_APPRAISAL_TAG tag left join USER_REG_INFO reg on tag.APPRAISAL_USER_ID = reg.APPRAISAL_USER_ID left join DISTRICT_LIST d on reg.company = d.SCHOOL_ID where tag.ACTIVITY_ID=? and d.ID in ("+ districtIds + ")";
            System.out.println(testSQL);
            testCount = jdbcTemplate.queryForObject(testSQL, new Object[] { ACTIVITY_ID }, Integer.class);
        }
        model.addAttribute("ParticipantsCount", participantsCount);
        model.addAttribute("ParticipantsTestCount", participantsTestCount);
        model.addAttribute("MaleCount", maleCount);
        model.addAttribute("FemaleCount", femaleCount);
        
        model.addAttribute("TestCount", testCount);
        model.addAttribute("CsTotal", csTotal);
        model.addAttribute("FsTotal", fsTotal);
        model.addAttribute("FsFTotal", fsFTotal);
        model.addAttribute("JsTotal", jsTotal);
        model.addAttribute("JsFTotal", jsFTotal);
        // int WorksCount = userBackstageService.getWorksCount(ACTIVITY_ID,"1",0,true);//获取该活动作品数
        // model.addAttribute("WorksCount", WorksCount);
        // int anumber = userBackstageService.getAnumber(ACTIVITY_ID);//获取活动审核通过作品数
        // int snumber = userBackstageService.getSnumber(ACTIVITY_ID);//获取提交作品总数
        // int fnumber = userBackstageService.getFnumber(ACTIVITY_ID);//获取决赛作品总数
        // int Pnumber = userBackstageService.getPnumber(ACTIVITY_ID);//获取决赛作品总数
        // model.addAttribute("anumber",anumber);//获取活动审核通过作品数
        // model.addAttribute("snumber",snumber);//获取提交作品总数
        // model.addAttribute("fnumber",fnumber);//获取决赛作品总数
        // model.addAttribute("Pnumber",Pnumber);//获取获奖作品总数
        model.addAttribute("Visit",activity.getACTIVITY_VISIST());//总浏览数
        model.addAttribute("like", activity.getVOTES_NUMBER());//总点赞数
        return "back/index/account_work_details";
    }

    /**
     * 后台数据统计
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/getAccountWorkDetails")
    public String getAccountWorkDetails(HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        HashMap<String, Object> map = new HashMap<>();
        List<DistrictListUserWorkVo> list = userBackstageService.getAccountWorkDetails(ACTIVITY_ID);
        map.put("code", 0);
        map.put("data", list);
        return JsonUtil.objectToJson(map);
    }
    
    @ResponseBody
    @RequestMapping("/IS_OPEN_YDCP")
    public int IS_OPEN_YDCP(int IS_OPEN_YDCP, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setIsOpenYdcp(IS_OPEN_YDCP, ACTIVITY_ID);
    }

    @ResponseBody
    @RequestMapping("/YDCP_NUM")
    public int YDCP_NUM(int YDCP_NUM, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setYdcpNum(YDCP_NUM, ACTIVITY_ID);
    }

    @ResponseBody
    @RequestMapping("/ORDER_RULE")
    public int ORDER_RULE(int ORDER_RULE, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setOrderRule(ORDER_RULE, ACTIVITY_ID);
    }

    @ResponseBody
    @RequestMapping("/deptUpdate")
    public int deptUpdate(@RequestBody Activity activity, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        return userBackstageService.deptUpdate(activity);
    }

    @ResponseBody
    @RequestMapping("/groupRuleUpdate")
    public int groupRuleUpdate(@RequestBody Activity activity, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        if (activity.getGroupRuleInfos() != null && activity.getGroupRuleInfos().size() != 0) {
            for (int i = 0; i < activity.getGroupRuleInfos().size(); i++) {
                GroupRule groupRule = activity.getGroupRuleInfos().get(i);
                groupRule.setACTIVITY_ID(ACTIVITY_ID);
                groupRule.setGROUP_RULE_TYPE(activity.getGROUP_RULE_TYPE());
                userBackstageService.addGroupRule(groupRule);
            }
        }
        return userBackstageService.groupRuleUpdate(activity);
    }

    @ResponseBody
    @RequestMapping("/addMessage")
    public int addMessage(@RequestBody Message message, HttpSession session) {
        message.setIS_READ(0);
        UserRegInfo userRegInfo = new UserRegInfo();
        userRegInfo.setID(message.getREG_ID());
        userRegInfo.setCUR_STATUS(message.getCUR_STATUS() + 1);
        return userBackstageService.addMessage(message,userRegInfo);
    }

    @ResponseBody
    @RequestMapping("/deleteGroupRule")
    public int deleteGroupRule(Integer groupRuleId, HttpSession session) {
        return userBackstageService.deleteGroupRule(groupRuleId);
    }

    /**
     * 设置投票开启情况
     * @param IS_VOTE
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/IS_VOTE")
    public int IS_VOTE(int IS_VOTE,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setIsVote(IS_VOTE,ACTIVITY_ID);
    }

    /**
     * 设置该活动上传作品数量
     * @param WORKS_LIMIT_PERUSER
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/WORKS_LIMIT_PERUSER")
    public int WORKS_LIMIT_PERUSER(int WORKS_LIMIT_PERUSER,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setWorkNumber(WORKS_LIMIT_PERUSER,ACTIVITY_ID);
    }

    /**
     * 每天点赞次数
     * @param VOTES_LIMIT_PERDAY
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/VOTES_LIMIT_PERDAY")
    public int VOTES_LIMIT_PERDAY(int VOTES_LIMIT_PERDAY,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        redisService.setVotesLinitPerday(VOTES_LIMIT_PERDAY,ACTIVITY_ID);
        return userBackstageService.setVotesLinitPerday(VOTES_LIMIT_PERDAY,ACTIVITY_ID);
    }

    /**
     * 每天对同一作品点赞次数
     * @param VOTES_LIMIT_TOSINGLE_PERDAY
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/VOTES_LIMIT_TOSINGLE_PERDAY")
    public int VOTES_LIMIT_TOSINGLE_PERDAY(int VOTES_LIMIT_TOSINGLE_PERDAY,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        redisService.setVotesLimitTosinglePerday(VOTES_LIMIT_TOSINGLE_PERDAY,ACTIVITY_ID);
        return userBackstageService.setVotesLimitTosinglePerday(VOTES_LIMIT_TOSINGLE_PERDAY,ACTIVITY_ID);
    }

    /**
     * 每天对同一作品点赞次数
     * @param CURRENT_STAGE
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/CURRENT_STAGE")
    public int CURRENT_STAGE(int CURRENT_STAGE,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setCurrentStage(CURRENT_STAGE,ACTIVITY_ID);
    }

    /**
     * 作品类型
     * @param V_TYPE
     * @param A_TYPE
     * @param F_TYPE
     * @param P_TYPE
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/WORK_TYPE")
    public int WORK_TYPE(Integer V_TYPE,Integer A_TYPE,Integer F_TYPE,Integer P_TYPE,HttpSession session){
        if(V_TYPE==null)V_TYPE=0;
        if(A_TYPE==null)A_TYPE=0;
        if(F_TYPE==null)F_TYPE=0;
        if(P_TYPE==null)P_TYPE=0;
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setWorkType(V_TYPE,A_TYPE,F_TYPE,P_TYPE,ACTIVITY_ID);
    }


    /**
     * 限制报名
     * @param IS_SIGUP
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/IS_SIGUP")
    public int IS_SIGUP(int IS_SIGUP,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setIsSigup(IS_SIGUP,ACTIVITY_ID);
    }
    /**
     * 手机端显示情况
     * @param DELETED
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/DELETED")
    public int DELETED(int DELETED,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setDELETED(DELETED,ACTIVITY_ID);
    }
    /**
     * 手机端显示获奖名单情况
     * @param WINNERS
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/WINNERS")
    public int WINNERS(int WINNERS,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setWINNERS(WINNERS,ACTIVITY_ID);
    }
    /**
     * 手机端是否进入该活动
     * @param IS_IN
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/IS_IN")
    public int IS_IN(int IS_IN, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setIS_IN(IS_IN, ACTIVITY_ID);
    }

    /**
     * 手机端是否显示评论
     * 
     * @param IS_SHOW_COMMENT
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/IS_SHOW_COMMENT")
    public int IS_SHOW_COMMENT(int IS_SHOW_COMMENT, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setIS_SHOW_COMMENT(IS_SHOW_COMMENT, ACTIVITY_ID);
    }
    /**
     * 活动状态
     * @param ACTIVITY_STATE
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/ACTIVITY_STATE")
    public int ACTIVITY_STATE(int ACTIVITY_STATE,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setACTIVITY_STATE(ACTIVITY_STATE,ACTIVITY_ID);
    }

    /**
     * 提交作品数量
     * @param SUBMIT_WORK_NUMBER
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/SUBMIT_WORK_NUMBER")
    public int SUBMIT_WORK_NUMBER(int SUBMIT_WORK_NUMBER,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setSubmitWorkNumber(SUBMIT_WORK_NUMBER,ACTIVITY_ID);
    }

    /**
     * 管理员是否提交作品
     * @param IS_SUBMIT
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/IS_SUBMIT")
    public int IS_SUBMIT(int IS_SUBMIT,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setSubmit(IS_SUBMIT,ACTIVITY_ID);
    }
    /**
     * 该活动是否设置投票
     * @param IS_ROTE
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/IS_ROTE")
    public int IS_ROTE(int IS_ROTE, HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        return userBackstageService.setIsRote(IS_ROTE, ACTIVITY_ID);
    }

    @ResponseBody
    @RequestMapping("/GEN_ACTIVITY_CODE")
    public String GEN_ACTIVITY_CODE(HttpSession session) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        String bizCode = userBackstageService.getDistrictBizById(ad.getDISTRICT_ID());
        String sql = "select * from [classificationofreading].[dbo].[mp_info] where mp_app_id=?";
        Map<String, Object> mpInfoMap = jdbcTemplate.queryForMap(sql, APP_ID_B_CLIENT_NEW);
        String accessToken = mpInfoMap.get("ACCESS_TOKEN") + "";
        String qrcode = MPUtils.getActivityQRCode(ACTIVITY_ID + "", bizCode, accessToken);
        Activity activity = new Activity();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        activity.setACTIVITY_CODE(qrcode);
        userBackstageService.updateQrcode(activity);
        Activity activity1 = userBackstageService.getActivityById(ACTIVITY_ID);
        return activity1.getACTIVITY_CODE();
    }
    
    /**
     * 修改作品封面
     * @param model
     * @return
     */
    @RequestMapping("/editorWork")
    public String editorWork(int WORK_ID,Model model){
        String picName = userBackstageService.getPicName(WORK_ID);
        model.addAttribute("picName",picName);
        model.addAttribute("WORK_ID",WORK_ID);
        return "back/index/editor_work";
    }

    /**
     * 修改作品信息(显示)
     * @param model
     * @return
     */
    @RequestMapping("/editorWorkDetails")
    public String editorWorkDetails(int WORK_ID,Model model,HttpSession session){
        UserWorkVo work = userBackstageService.getWorkDetail(WORK_ID);
        model.addAttribute("work",work);
        model.addAttribute("WORK_ID",WORK_ID);
//        Administrators ad =(Administrators)session.getAttribute("ADMIN");
//        List<DistrictList> districtLists = userBackstageService.getCounty();//获取全部地址
//        model.addAttribute("districtLists", districtLists);
//        List<Activity> activities = userBackstageService.getAllActivities();//获取全部活动
//        model.addAttribute("activities", activities);
        return "back/index/update_work";
    }

    /**
     * 查看图片作品信息(显示)
     * @param model
     * @return
     */
    @RequestMapping("/SearchPic")
    public String SearchPic(int WORK_ID,Model model){
        UserWorkVo work = userBackstageService.getWorkDetail(WORK_ID);
        model.addAttribute("work",work);
        return "back/index/search_work";
    }

    /**
     * 修改作品信息（修改）
     * @param work
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/backUpdateWork")
    public int backUpdateWork(UserWorkVo work,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        work.setACTIVITY_ID(ACTIVITY_ID);
        return userBackstageService.backUpdateWork(work);
    }

    /**
     * 后台修改作品图片
     * @param work
     * @return
     */
    @ResponseBody
    @RequestMapping("/backEditorWork")
    public int backEditorWork(Work work){
        return userBackstageService.backEditorWork(work);
    }




    /**
     * 删除奖项
     * @param PrizeId
     * @return
     */
    @ResponseBody
    @RequestMapping("/deletePrize")
    public int deletePrize(Integer PrizeId,HttpSession session){
        return userBackstageService.deletePrize(PrizeId);
    }

    /**
     * 范文列表
     * @return
     */
    @RequestMapping("/article")
    public String toArticle(Model model,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        model.addAttribute("isSup",isSup);
        return "back/index/article_management";
    }

    /**
     * 获取范文列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/getArticles")
    public String getArticles(@RequestParam(required=false,defaultValue="1") int page,
                              @RequestParam(required=false,defaultValue="9")int limit,
                              String name){
         HashMap<String,Object> map = new HashMap<>();
        PageInfo<Article> articles = userBackstageService.getReadWork(page,limit,name);
        map.put("code",0);
        map.put("name",name);
        map.put("articles",articles);
        return JsonUtil.objectToJson(map);
    }

    /**
     * 根据ID删除范文
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteArticle")
    public int deleteArticle(Integer ID){
        return userBackstageService.deleteArticle(ID);
    }


    /**
     * 根据ID修改范文
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateArticle")
    public int updateArticle(Article article){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        return userBackstageService.updateArticle(article,mp);
    }

    /**
     * 添加范文
     * @return
     */
    @ResponseBody
    @RequestMapping("/addArticle")
    public int addArticle(Article article){
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        return userBackstageService.addArticle(article,mp);
    }

    /**
     * 根据ID显示范文
     * @return
     */
    @ResponseBody
    @RequestMapping("/getArticle")
    public String getArticle(Integer ID){
        HashMap<String,Object> map = new HashMap<>();
        Article article = userBackstageService.getArticle(ID);
        map.put("code",0);
        map.put("article",article);
        return JsonUtil.objectToJson(map);
    }


    //获取范文内容
    @ResponseBody
    @RequestMapping("/getHtml")
    String getHtml(@RequestParam(required = false) String url) {
        HashMap<String,Object> map = new HashMap<>();
        if(url != null && !"".equals(url)){
            map.put("code",1);
            map.put("data", Utils.getHtml(url));
            return JsonUtil.objectToJson(map);
        }
        map.put("code",0);
        return JsonUtil.objectToJson(map);
    }

    /**
     * 设置奖项
     * 参数  奖项id
     *       作品id
     */
    @ResponseBody
    @RequestMapping("/setPrize")
    public int setPrize(Prize prize,HttpSession session) {
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        //查询该奖项是否在设置完
        boolean falg = userBackstageService.islosePrize(prize,ACTIVITY_ID);
        if(falg){//添加奖项并设置状态加一
            //设置奖项
            return userBackstageService.setWorkPrize(prize);
        }else{
            return 2;
        }
    }

    /**
     * 设置奖项
     * 参数  奖项id
     *       作品id
     */
    @ResponseBody
    @RequestMapping("/delPrize")
    public int delPrize(Prize prize) {
        return userBackstageService.delWorkPrize(prize);
    }

    /**
     * 设置奖项
     * 参数  奖项id
     *       作品id
     */
    @ResponseBody
    @RequestMapping("/award")
    public int award(int WORK_ID) {
        return userBackstageService.award(WORK_ID);
    }
    /**
     * 修改奖项规则
     * @param activity
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateActivityRules")
    public String updateActivityRules(Activity activity,HttpSession session){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        activity.setACTIVITY_ID(ACTIVITY_ID);
        int res = userBackstageService.updateActivityRules(activity);
        if(res>0) {
            return "success";
        }
        return "fail";
    }

    @ResponseBody
    @RequestMapping("/updateProbtation")
    public String updateProbtation(Probation probation){
        int res = userBackstageService.updateProbtation(probation);
        if(res>0) {
            return "success";
        }
        return "fail";
    }

    @RequestMapping("/prizeMsg")
    public String prizeMsg(HttpSession session,Model model){
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        PrizeUser prizeUser = userBackstageService.getPrizeUser(ACTIVITY_ID);
        model.addAttribute("prizeUser",prizeUser);
        return "back/index/PrizeUser";
    }

    @ResponseBody
    @RequestMapping("/upPrizeUser")
    public int upPrizeUser(HttpSession session, PrizeUser prizeUser) {
        Administrators ad = (Administrators) session.getAttribute("ADMIN");
        int ACTIVITY_ID = ad.getLAST_ACTIVITY_ID();
        prizeUser.setACTIVITY_ID(ACTIVITY_ID);
        return userBackstageService.setPrizeUser(prizeUser);
    }
    
    private void getChildrenIds(Integer districtId, List<Integer> districtIdList) {
        // 递归获取该地区下的所有地区
        List<DistrictList> list = userBackstageService.getCountys(districtId);
        if (null != list && list.size() > 0) {
            for (DistrictList dl : list) {
                districtIdList.add(dl.getID());
                getChildrenIds(dl.getID(), districtIdList);
            }
        }
    }
}
